//
//  NNInputView.swift
//  CommonTool
//
//  Created by tenroadshow on 11.3.22.
//

import UIKit




var kCustomInputViewKey: UInt8 = 0
public extension UIViewController {
    
    var customInputView: NNInputView? {
        set {
            objc_setAssociatedObject(self, &kCustomInputViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &kCustomInputViewKey) as? NNInputView
        }
    }
    
    // 添加键盘监听通知
    func addKeyboardNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(notification:)),
                                               name: UIResponder.keyboardWillShowNotification,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillHidden(notification:)),
                                               name: UIResponder.keyboardWillHideNotification,
                                               object: nil)
    }
    
    // 移除键盘监听通知
    func removeKeyboardNotification() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func keyboardWillShow(notification: Notification) {
        customInputView?.keyboardWillShow(notification: notification)
    }
    
    @objc func keyboardWillHidden(notification: Notification) {
        customInputView?.keyboardWillHidden(notification: notification)
    }
    
}






public class NNInputView: UIView {
    
    private lazy var textViewContainer: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "F2F2F2")
        return view
    }()
    
    private lazy var customTextView: UITextView = {
        let textView = UITextView(frame: CGRect(x: 0, y: 0, width: CC.screenW, height: 20))
        textView.returnKeyType = .done
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.textColor = UIColor.black
        textView.delegate = self
        textView.textContainerInset = .zero
        textView.backgroundColor = .cyan
        return textView
    }()

    private lazy var effectView: UIView = {
        let effectView = UIView(frame: CGRect(x: 0, y: 0, width: CC.screenW, height: CC.screenH))
        effectView.isUserInteractionEnabled = true
        effectView.backgroundColor = UIColor(white: 0, alpha: 0.15)
        effectView.addGestureRecognizer(self.tapGesture)
        return effectView
    }()
    
    private lazy var tapGesture: UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer(target: self, action: #selector(effectViewTapAction(tap:)))
        return tap
    }()

    private var completeHandle: ((String?) -> ())?
        
    convenience init(contentHeight: CGFloat) {
        self.init(frame: CGRect(x: 0, y: CC.screenH, width: CC.screenW, height: contentHeight))
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = UIColor(hexString: "F2F2F2")
        
        addSubview(textViewContainer)
        textViewContainer.addSubview(customTextView)

        textViewContainer.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 100))
        }
        customTextView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    
    func show(content: String? = nil, completeHandle: @escaping ((String?) -> ())) {
        
        guard let keywindow = UIApplication.shared.delegate?.window else { return }
        
        self.customTextView.frame = self.bounds
        if let text = content, !text.isEmpty {
            self.customTextView.text = text
        }else {
            self.customTextView.text = "请输入文本"
        }

        keywindow?.addSubview(self)
        keywindow?.bringSubviewToFront(self)
        
        self.completeHandle = completeHandle
        if customTextView.canBecomeFirstResponder {
            customTextView.becomeFirstResponder()
        }
    }

}

// 事件
extension NNInputView {
    
    @objc func keyboardWillShow(notification: Notification) {
        guard let userInfo = notification.userInfo else { return }
        guard let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return }

        guard let parentView = superview else { return }
        parentView.insertSubview(effectView, belowSubview: self)
        effectView.frame = parentView.bounds
        effectView.alpha = 0.0
        UIView.animate(withDuration: duration) {
            self.frame = CGRect(x: 0,
                                y: keyboardFrame.minY - self.frame.size.height,
                                width: keyboardFrame.width,
                                height: self.frame.size.height)
            self.effectView.alpha = 1.0
        }
    }
    
    @objc func keyboardWillHidden(notification: Notification) {
        guard let userInfo = notification.userInfo else { return }
        guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return }
        self.effectView.alpha = 1.0
        UIView.animate(withDuration: duration) {
            self.frame = CGRect(x: 0, y: CC.screenH, width: CC.screenW, height: self.frame.size.height)
            self.effectView.alpha = 0.0
        } completion: { _ in
            self.effectView.removeFromSuperview()
            self.removeFromSuperview()
        }
    }
    
    // 取消键盘
    @objc func effectViewTapAction(tap: UITapGestureRecognizer) {
        self.customTextView.resignFirstResponder()
    }
}


// UITextViewDelegate
extension NNInputView: UITextViewDelegate {
    
    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.textInputMode?.primaryLanguage == "emoji" {
            return false
        }
        if text == "\n" {
            textView.resignFirstResponder()
        }
        return textView.inputRestrictions(shouldChangeTextIn: range, replacementText: text, maxCharacters: 100, regex: NNRegexType.isChineseDigitalAndLetterAndMore.rawValue)
    }
    
    
    public func textViewDidChange(_ textView: UITextView) {
        self.completeHandle?(textView.text.trimmingCharacters(in: .whitespacesAndNewlines))
    }
}
